package com.etung.iot.demo.storage;

import com.etung.iot.demo.dao.RealDataMapper;
import com.etung.iot.demo.modles.RealData;
import com.etung.iot.demo.modles.StorageEntity;
import com.etung.iot.demo.storage.constorage.TriggerConditionStoreRule;
import com.etung.iot.demo.utils.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Storage(StorageConstant.SAMPLING_PERIOD_STORAGE)
public class SamplePeriodRule implements StorageHandler {
    @Autowired
    private StorageRuleUtil storageRuleUtil;
    @Autowired
    private RealDataMapper realDataMapper;
    @Autowired
    private ConStorageSelector conStorageSelector;

    @Override
    public void handler(RealData realData) {
        StorageEntity storageRule = storageRuleUtil.getStorageRule(realData.getImei(), realData.getVarId());
        Integer samplingPeriodType = storageRule.getSamplingPeriod();
        int cycleMin = 0;
        if (!StringUtils.isEmpty(samplingPeriodType)) {
            cycleMin = SamplePeriodEnum.getTimeByType(samplingPeriodType);
        }
        Long lastStoreTimestamp = storageRuleUtil.getLastStoreTimestamp(realData.getImei(), realData.getVarId());
        if (realData.getTime().getTime() - lastStoreTimestamp >= cycleMin * 60 * 1000) {
            realDataMapper.insert(realData);
            storageRuleUtil.saveLastStoreTimestamp(realData.getImei(), realData.getVarId(), realData.getTime().getTime());
        } else {
            conStorageSelector.saveConditionRealData(realData);
        }
    }
}
